<?php

    namespace Home\Event;
    use Think\Controller;

    class UserEvent extends Controller
    {
        //注册处理
        public function regDo ()
        {
            if(IS_POST){
                //判断验证码是否正确
                $verify = new \Think\Verify();
                if(!$verify->check(I("post.vcode"), "")){
                    $this->error("验证码不正确");
                }
                $data['name'] = I("post.name");
                $data['sex'] = I("post.sex");
                $data['pwd'] = md5(I("post.pwd"));
                $data['tel'] = I("post.tel");
                $data['email'] = I("post.email");
                $data['create_time'] = date("Y-m-d H:i:s");
                $data['login_time'] = date("Y-m-d H:i:s");

                $user = M("user");
                $id = $user -> add($data);
                if($id > 0){
                    session(null);
                    $home["id"] = $id;
                    $home["name"] = $data['name'];
                    session("home",$home);
                    return true;
                }else{
                    return false;
                }


            }
        }

        //登录验证
        public function loginDo ()
        {
            if(IS_POST){
                //判断验证码是否正确
                $verify = new \Think\Verify();
                if(!$verify->check(I("post.vcode"), "")){
                    $this->error("验证码不正确");
                }
                $name = I("post.name");
                $pwd = md5(I("post.pwd"));
                $user = M("user");
                $userinfo = $user -> field(array("id","pwd","user_img")) ->where("name='$name'")  ->find();
                if(empty($userinfo)){
                    $this->error("用户名不存在");
                }
                if($pwd != $userinfo['pwd']){
                    $this->error("密码不正确");
                }
                session(null);
                //更新最近一次登录时间
                $data['login_time'] = date("Y-m-d H:i:s");
                $user->where("name='$name'")->save($data);
                $user->where("name='$name'")->setInc('login_num',1);
                $home["id"] = $userinfo['id'];
                $home["name"] = $name;
                $home["user_img"] = $userinfo['user_img'];
                session("home",$home);
                return true;
            }
        }

        //领取优惠券
        public function getCoupon ()
        {
            //用户id;
            $id = session('home')['id'];
            //优惠券id
            $coupon_id = I("get.coupon_id");



            //1. 查询该用户是否已经有过该优惠券

            $userCoupon = M("user_coupon");
            $res = $userCoupon->where("coupon_id=$coupon_id and user_id=$id")->find();
            if($res){
                $this->error("每个优惠券只能领取一个哦!!!");
            }

            //如果没有
            $data['user_id'] = $id;
            $data['coupon_id'] = $coupon_id;
            $data['create_time'] = date("Y-m-d H:i:s");

            $insert_id  = $userCoupon->add($data);

            if($insert_id > 0){
                //如果领取成功,就把优惠券表里面的数量变更
                // num - 1  receive_num+1
                $coupon = M("coupon");
                $coupon->where("id=$coupon_id")->setDec("num",1);
                $coupon->where("id=$coupon_id")->setInc("receive_num",1);
            }
            return $insert_id;
        }

        //把商品添加到购物车
        public function addCart ()
        {
            //用户id;
            $id = session('home')['id'];
            $data['user_id'] = $id;
            //商品id
            $data['goods_id'] = I("post.goods_id");
            //商品名
            $data['goods_name'] = I("post.goods_name");
            //商品价格
            $data['price'] = I("post.price");

            //商品数量
            $data['num'] = I("post.qty");
            $data['create_time'] = date("Y-m-d H:i:s");

            //1. 先看看购物车是否有该商品的存在,
            //如果有,在原有的基础是更新,没有就添加进去
            $cart = M("cart");
            $goods_id = $data['goods_id'];
            $goodinfo = $cart
                ->field(['id'])
                ->where("goods_id = $goods_id and user_id = $id")
                ->find();
            if($goodinfo){
                //更新到购物车
                $cart_id = $goodinfo['id'];
                $num = (int)$data['num'];
                $row = $cart
                    ->where("id=$cart_id")
                    ->setInc("num",$num);
                return $row;
            }
            //添加到购物车
            $insert_id = $cart -> add($data);
            return $insert_id;
        }

        //根据id查询该用户购物车里面的商品
        public function showCart ()
        {
            if(IS_GET){
                //用户id
                $user_id = session("home")['id'];
                $cart = M("cart");
                $cartList = $cart
                    ->alias("c")->join("shopping_goodsimg i on c.goods_id = i.goods_id")
                    ->join("shopping_goods g on c.goods_id = g.id")
                    ->field(["g.id","c.user_id","c.num","c.price","c.goods_name","i.img","g.num goods_num"])
                    ->where("c.user_id=$user_id and i.is_main=1")->select();
                return $cartList;
            }
        }

        //新建地址
        public function addAddress ()
        {
            //用户id
            $data['user_id'] = session('home')['id'];
            $user_id = session('home')['id'];
            $data['name'] = I("get.name");
            $data['tel'] = I("get.tel");
            $data['address'] = I("get.content");
            $data['create_time'] = date("Y-m-d H:i:s");

            //把首选地址去掉
            $address = M('useradd');
            //把首选地址去掉
            $order['is_default'] = 0;
            $address->where("is_default =1 and user_id = $user_id")
                ->save($order);
            $address ->add($data);

        }

        //查询所有地址
        public function showAddress ()
        {
            //用户id
            $user_id = session('home')['id'];

            $address = M('useradd');
            $addressList = $address ->where("user_id=$user_id")->select();
            return $addressList;
        }

        //设默认地址
        public function setDefault ()
        {
            //用户id
            $user_id = session('home')['id'];
            //地址id
            $id = I("get.id");
            $address = M('useradd');
            //先把默认的去掉
            $order['is_default'] = 0;
            $address->where("is_default =1 and user_id = $user_id")
                ->save($order);
            //再更改新的默认
            $row = $address ->where("user_id=$user_id and id=$id")->setField("is_default",1);
            return $row;
        }

        //购物车中的商品数量发生变动时,就直接把数量更新到购物车
        public function updateCart ()
        {
            //用户id
            $user_id = session('home')['id'];
            //商品id
            $goods_id = I("get.goods_id");
            //商品数量
            $num = I("get.num");

            $data['num'] = $num;
            $cart = M("cart");
            $cart -> where("user_id=$user_id and goods_id=$goods_id")->save($data);
        }

        //购物车中删除单个商品
        public function delCart ()
        {
            //用户id
            $user_id = session('home')['id'];
            //商品id
            $goods_id = I("get.goods_id");
            $cart = M("cart");
            $row = $cart -> where("user_id=$user_id and goods_id=$goods_id")->delete();
            return $row;

        }

        //清空购物车
        public function delAllCart ()
        {
            //用户id
            $user_id = session('home')['id'];
            $cart = M("cart");
            $row = $cart -> where("user_id=$user_id")->delete();
            return $row;

        }

        //确认订单页面
        public function  confirmOrder ()
        {
            //用户id
            $user_id = session('home')['id'];
            //action 判断是从购物车页面购买,还是直接购买
            $action = empty(I("post.act")) ? "buy" : I("post.act");
            //如果从购物车购买,在获取多个商品的id
            if($action == "cart"){
                //获取商品id
                $goods_id = explode(",",I("post.goods_id"));
                foreach($goods_id as $id){
                    //根据商品id从购物车中查询详细信息
                    $cart = M("cart");
                    $cartinfo = $cart
                        ->alias("c")->join("shopping_goodsimg i on i.goods_id=c.goods_id")
                        ->where("c.goods_id=$id and c.user_id=$user_id and i.is_main=1")
                        ->field(array("c.goods_id id","c.goods_name","c.num","c.price","i.img"))
                        ->find();
                    $cartList[] = $cartinfo;

                }
                return $cartList;
            }elseif($action == "buy"){
                //获取商品id
                $goods_id = I("post.goods_id");
                //根据图片id查看商品的封面图
                $img = M("goodsimg");
                $img = $img->where("is_main=1")->getFieldByGoods_id($goods_id,"img");
                $data['id'] = $goods_id;
                $data['goods_name'] = I("post.goods_name");
                $data['num'] = I("post.qty");
                $data['goods_type'] = I("post.goods_type");
                $data['price'] = I("post.price");
                $data['img'] = $img;
//                dump($data);die;
                $cartList[] = $data;
                return $cartList;
            }
        }

        //通过用户id查询他的所有优惠券
        public function queryAllCoupon ()
        {
            //用户id
            $user_id = session('home')['id'];
            $coupon = M("coupon")
                ->alias("c")->join("shopping_user_coupon u on c.id=u.coupon_id")
                ->where("u.user_id=$user_id and c.is_lose=1 and u.is_use=0")
                ->field(array('c.name','c.min_pri','c.cou_pri','c.id'))
                ->order("c.min_pri")
                ->select();
            return $coupon;

        }

        //用户积分增加,如果用户在积分表中已存在,就更新积分
        public function updataIntegral($msg,$num){

            //用户id
            $user_id = session('home')['id'];
            //根据用户id查询积分表
            $integral = M("integral");
            $res = $integral->field(array("num","integral_id"))->where("user_id = $user_id")->find();
            if(empty($res)){
                $data['user_id'] = $user_id;
                //设置积分唯一id
                $data['integral_id'] = date("Ymd").uniqid();
                //积分数量
                $data['num'] = $num;
                $data['create_time'] = date('H-m-d H:i:s');
                $row = $integral->add($data);
                if($row > 0){
                    $integralDetail = M("integraldetail");
                    unset($data['user_id']);
                    unset($data['create_time']);
                    $data['msg'] = $msg;
                    $integralDetail->add($data);
                }
            }else{
                //用户已存在,则直接更新

                $data['num'] = $res['num']+$num;
                $row = $integral->where("user_id=$user_id")->save($data);

                if($row > 0){
                    $integralDetail = M("integraldetail");
                    $data['num'] = $num;
                    $data['integral_id'] = $res['integral_id'];
                    $data['msg'] = $msg;

                    $integralDetail->add($data);
                }
            }

            //如果添加或跟新成功,则向积分详情表添加

        }

        //根据用户id查询积分
        public function queryIntegral ()
        {
            //用户id
            $user_id = session('home')['id'];
            //根据用户id查询积分表
            $integral = M("integral");
            $res = $integral->field(array("num"))->where("user_id = $user_id")->find();
            return $res;
        }

        //提交订单
        public function commitOrder ()
        {
            //用户id
            $user_id = session('home')['id'];
            //判断有没有收货地址
             if(empty(I("post.address"))){
                $this->error("没有地址!!!");
             }
            $address_id = I("post.address");
            //根据收货地址id 查地址名和收货人和联系电话
            $address = M("useradd");
            $addressinfo = $address ->field(array("name","address","tel"))->where("user_id=$user_id and id=$address_id")->find();
            $data["address_username"] = $addressinfo['name'];
            $data["address_name"] = $addressinfo['address'];
            $data["address_tel"] = $addressinfo['tel'];
            //dump($data);
//            dump(I("post.coupon_id"));die;
            //判断是否使用后优惠券

            if(I("post.coupon_id") > 0){
                //获取优惠券id,并查看该优惠券减免的价格
                $coupon_id = I("post.coupon_id");
                $coupon = M("coupon");
                $res = $coupon->where("id=$coupon_id")->field(array("cou_pri"))->find();
                $coupri = $res['cou_pri'];
                $orderData['is_coupon'] = 1;
                $orderData['coupon_id'] = $coupon_id;
                $data['is_coupon'] = $coupri;
                //如果该优惠就已使用,就给用户优惠券表的is_use设为1
                $userCoupon = M('user_coupon');
                $userCoupon->where("user_id=$user_id and coupon_id=$coupon_id")->setField("is_use",1);
//                echo $coupon;die;
            }else{
                $coupri = 0;
            }
            //判断是否使用积分减免
            if(I("post.inte") > 0){
                //获取积分减免的价格
                $integral = M("integral");
                $res = $integral->where("user_id=$user_id")->field(array("num"))->find();
                $integralPri = $res['num']/100;
                $orderData['is_integral'] = 1;
                $orderData['integral_num'] = $res['num'];
                $data['is_integral'] = $integralPri;
                //如果使用了积分
                //积分详情表操作记录积分使用的原因
                $num = $res['num'];
                $this->updataIntegral('购物所用',-$num);
            }else{
                $integralPri = 0;
            }
            //dump($integralPri);

            //循环post获取商品id和对应购买数量
            foreach($_POST as $key => $value){
                if(substr_count($key,"goods_id") > 0){
                    $goods_id[] = str_replace("goods_id","",$key);
                }
            }
//            dump($goods_id);die;

            //获得因给支付的总价格
            $total = 0;
            $type = $_POST['goods_type'];
            foreach($goods_id as $key => $val){
                //根据商品id查商品价格
//                dump($_POST);die;
                //判断商品类型
                if($type==1){
                    //抢购商品
                    $goods = M('seckill');
                    $goodsinfo = $goods->where("goods_id=$val")->field(array("seck_pri"))->find();
//                    dump($goodsinfo);die;
                    $goods_price[$key] = $goodsinfo['seck_pri'];

                }elseif($type==2){
                    //拼单商品
                    $uid = $_POST['uid'];
                    $goods = M('group');
                    $goodsinfo = $goods->where("goods_id=$val")->field(array("gprice"))->find();
//                    dump($goodsinfo);die;
                    $goods_price[$key] = $goodsinfo['gprice'];

                }else{
                    //普通商品
                    $goods = M('goods');
                    $goodsinfo = $goods->where("id=$val")->field(array("price"))->find();
                    $goods_price[$key] = $goodsinfo['price'];
                }

                //数量
                $goods_num[$key] = I("post.goods_num".$val);
                $total = $goods_price[$key] * I("post.goods_num".$val);
//                dump($total);die;
            }

            $total = $total - $coupri - $integralPri;
            //echo $total;die;
            //生成唯一订单id
            $order_id = date("Ymd").uniqid().mt_rand(0,100);
            if(($type == 0) or ($type==1)){
                //添加普通商品或秒杀商品数据到数据库
                $orderData["price"] = $total;
                $orderData["order_id"] = $order_id;
                $orderData["user_id"] = $user_id;
                $orderData["address_id"] = $address_id;
                $orderData["create_time"] = date("Y-m-d H:i:s");
                //订单类型(团购用另一张订单表)
                $orderData["goods_type"] = $type==1?1:0;
                $order = M("order");
                //echo $orderData["price"];die;
                $res = $order->add($orderData);
                //返回自增id,如果添加成功,就继续添加到订单详情
                if($res > 0){
                    foreach($goods_id as $key => $val){
                        //根据订单唯一id插入数据
                        $orderDetail = M("orderdetail");
                        $orderDetailData['order_id'] = $order_id;
                        $orderDetailData['goods_id'] = $val;
                        $orderDetailData['num'] = $goods_num[$key];
                        $orderDetailData['price'] = $goods_price[$key];
                        $orderDetailData["create_time"] = date("Y-m-d H:i:s");
                        $orderDetail->add($orderDetailData);
                    }
                    $data["total"] = $total;
                    $data["order_id"] = $order_id;
                    if(I("post.act") == "cart"){
                        foreach($goods_id as $val) {
                            //商品id
                            $goods_id = $val;
                            $cart = M("cart");
                            $cart->where("user_id=$user_id and goods_id=$goods_id")->delete();
                        }
                    }


                    return $data;
                }else{
                    return "失败的订单";
                }
            }elseif($type==2){
                //拼团商品添加到拼团订单
                $uid=$_POST['uid'];
                $orderData["price"] = $total;
                $orderData["order_id"] = $order_id;
                $orderData["user_id"] = $user_id;
                $orderData["goods_id"] = $goods_id[0];
//                dump($goods_id[0]);die;
                $orderData["gnum"] = 1;
                $orderData["address_id"] = $address_id;
                $orderData["create_time"] = date("Y-m-d H:i:s");

                $order = M("grouporder");
                $res = $order->add($orderData);
                //返回自增id,如果添加成功,就继续添加到订单详情
                if($res > 0){
                    $data["total"] = $total;
                    $data["order_id"] = $order_id;
                    if(I("post.act") == "cart"){
                        foreach($goods_id as $val) {
                            //商品id
                            $goods_id = $val;
                            $cart = M("cart");
                            $cart->where("user_id=$user_id and goods_id=$goods_id")->delete();
                        }
                    }

                    $data['type'] = $type;
                    $data['gid']=$goods_id[0];
                    $data['uid']=$uid;
//                    dump($data);die;
                    return $data;
//                    return $uid;
                }else{
                    return "失败的订单";
                }

            }


        }

        //付款
        public function pay()
        {
            //团购发起人id
            $uid=$_GET['uid'];
            $gid = $_GET['gid'];
            //获得用户id
            $user_id = session('home')['id'];
            //获得订单唯一id
            $order_id = I("get.order_id");
            $data['is_pay'] = 1;
//            $data['is_ok'] = 1;
            if($_GET['type']==2){
                //团购的订单grouporder
                if($uid != null){
                    //有团购人发起
                    $data['uid'] = $uid;
                    $order = M("grouporder");
                    $row = $order->where("user_id='$user_id' and goods_id='$gid'")
                        ->save($data);
                    $order->where("user_id='$user_id' and goods_id='$gid'")->setInc('total_num',1);
                    $res_num = M('grouporder')->where("uid = $uid and goods_id='$gid'")->count();
                    if($res_num>4){
                        $this->error("拼团人数已满,不能加入",U("Index/index"));
                    }

                }else{
                    //没有团购人发起
                    $data['uid'] = $user_id;
                    $data['total_num'] = 1;
                    $order = M("grouporder");
                    $row = $order->where("user_id='$user_id' and goods_id='$gid'")
                        ->save($data);
                }

            }else{
                //普通订单与抢购订单order
                $order = M("order");
                $row = $order->where("user_id='$user_id' and order_id='$order_id'")
                    ->save($data);
                if($row > 0){
                    //通过订单id获得订单详情
                    $orderDetail = M("orderdetail");
                    $orderDetailList = $orderDetail->where("order_id='$order_id'")->select();
                    //循环订单详情,把付过款的商品数量在商品表中改变
                    $goods = M("goods");
                    foreach($orderDetailList as $value){
                        //商品id
                        $goods_id = $value["goods_id"];
                        //商品数量
                        $num = $value["num"];
                        //在查询一下商品库存
                        $stock = $goods->getFieldById($goods_id,"num");
                        if($stock < $num){
                            $this->error("库存不足,无法购买");
                        }
                        //如果库存充足
                        $goods->where("id=$goods_id")->setInc("sales_num",$num);
                        $goods->where("id=$goods_id")->setDec("num",$num);
                    }
                }
            }


            $tt=array(
                "uid"=>$user_id,
                "gid"=>$_GET['gid']
            );
            $type = $_GET['type'];
            if($row > 0){
                if(($type == 0)or $type==1){
                    $this -> success("付款成功",U("Index/index"));
                }elseif($type ==2){
                    if($res_num>4){
                        $this->error("拼团人数已满,不能加入",U("Index/index"));
                    }elseif($res_num<4){
                        $r1 = $order->where("user_id='$user_id' and goods_id='$gid' and is_status=1")
                            ->find();
                        if($r1>1){
                            $this->success("已拼过此商品,不能重复",U('Index/index'));
                        }else{
                            print_r("付款成功!<br/>拼团中...请将下面链接转发给朋友一起团购");
                            $url ="http://".HOST.U('Index/goodsDetails',array('id'=>$tt['gid'],'uid'=>$tt['uid']));
                            print_r("<a href='$url'>把我发送给好友吧</a>");
                            print_r("把我发送给好友吧:<input type='text' value='$url'>");
                        }

//                    dump($tt);
                    }elseif($res_num ==4){

                        $data['total_num'] = 0;
                        $data['is_status'] = 1;
                        $row = $order->where("user_id='$user_id' and goods_id='$gid'")
                            ->save($data);
                        $this->success("拼团成功",U('Index/index'));
                    }

                }else{
                    $this->display("未知错误",U("Index/index"));
                }
            }else{
                $this-> error("付款失败");
            }
        }
        //查看订单
        public function queryMyOrder()
        {
            //获得用户id
            $user_id = session('home')['id'];
            $order = M("order");
            $res = $order ->where("user_id=$user_id")->select();
            return $res;
        }
        //查看订单详情
        public function queryMyOrderDetail($orderList)
        {
            foreach($orderList as $key => $value){
                $order_id = $value['order_id'];
                $orderDetail = M("orderdetail");
                $res[$key] = $orderDetail
                    ->alias("o")->join("shopping_goodsimg i on i.goods_id=o.goods_id")
                    ->join("shopping_goods g on o.goods_id=g.id")
                    ->field(array("i.img","o.num","o.price","g.name","g.id","o.order_id","o.is_evaluate"))
                    ->where("o.order_id='$order_id' and i.is_main=1")->select();
            }
            return $res;
        }












    }